<?php

/**
 * Created by JiangJiaCai.
 * User: Administrator
 * Date: 2017/7/11 0011
 * Time: 21:26
 */
namespace ext\service;

use App\Models\QdcsConfig;
use com_jjcbs\lib\Service;
use ext\conf\SystemConfigMap;
use ext\dao\ConfigDaoImpl;

class ConfigServiceImpl extends Service
{
    public $configDaoImpl;

    public function __construct()
    {
        $this->configDaoImpl = new ConfigDaoImpl();
    }

    public function exec()
    {
        // TODO: Implement exec() method.
    }

    public function setArrayConfig(string $key , array $arr){
        $this->configDaoImpl->set($key , json_encode($arr , true));
    }

    public function setObjectConfig(string $key , $obj){
        $this->configDaoImpl->set($key , serialize($obj));
    }

    public function getArrayConfig(string $key) : array{
        return json_decode($this->configDaoImpl->get($key) , true);
    }

    public function getObjConfig(string $key){
        return unserialize($this->configDaoImpl->get($key));
    }

    /**
     * 安全的删除配置，请使用这个方法而不是ConfigDaoImpl
     * @param string $key
     */
    public function delConfig(string $key){
        if ( $this->isSystemKey($key)) throw new \Exception('系统配置项禁止删除！');
        $this->configDaoImpl->del($key);
    }

    public function getSystemConfig() : array{
        $data = [];
        $res = QdcsConfig::whereIn('config_key' , SystemConfigMap::$data)->get();
        foreach ($res as $configObj){
            $data[$configObj->config_key] = $configObj->config_val;
        }
        return $data;
    }

    public function delById(int $id){
        $config = QdcsConfig::whereKey($id)->first();
        $this->delConfig($config->config_key);
    }
    private function isSystemKey(string $key) : bool{
        return array_search($key , SystemConfigMap::$data) !== false;
    }


}